﻿using System;
using System.Threading;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using NLog;

namespace SessionHunter.Utilities
{
    /// <summary>
    /// Simplifies common tasks associated with UI behaviour, espcially multi-threaded actions in WPF
    /// </summary>
    public class UIHelper
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Initializes a new instance of the <see cref="UIHelper"/> class.
        /// </summary>
        /// <param name="isBackgroundThread">if set to <c>true</c> is running on background thread.</param>
        public UIHelper(bool isBackgroundThread = false)
        {
            IsBackgroundThread = isBackgroundThread;
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance is running on a background thread.
        /// </summary>
        public bool IsBackgroundThread
        {
            get;
            set;
        }

        /// <summary>
        /// Sends a message.  Will either be the current thread or the UI Dispatcher depending on IsBackgroundThread
        /// </summary>
        /// <typeparam name="TMessage">The type of the message.</typeparam>
        /// <param name="message">The message.</param>
        public void MessengerSend<TMessage>(TMessage message)
        {
            logger.Debug("MessengerSend [" + (IsBackgroundThread ? "Background" : "Main") + "] of type " + typeof(TMessage).Name);
            if (!IsBackgroundThread)
            {
                Messenger.Default.Send<TMessage>(message);
            }
            else
            {
                DispatcherHelper.UIDispatcher.BeginInvoke(new ThreadStart(() => Messenger.Default.Send<TMessage>(message)));
            }
        }

        /// <summary>
        /// Handles an exception by displaying the details in a friendly dialog
        /// </summary>
        /// <param name="logger">The class specific logger to use.</param>
        /// <param name="message">The message.</param>
        /// <param name="ex">The ex.</param>
        public void HandleException(Logger logger, string message, Exception ex)
        {
            logger.Debug("HandleException [" + (IsBackgroundThread ? "Background" : "Main") + "]");
            if (!IsBackgroundThread)
            {
                Helper.HandleException(logger, message, ex);
            }
            else
            {
                DispatcherHelper.UIDispatcher.BeginInvoke(new ThreadStart(() => Helper.HandleException(logger, message, ex)));
            }
        }
    }
}
